﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.Composition.Hosting;

namespace Host.Mef
{
    class MefControllerFactory : IControllerFactory
    {
        CompositionContainer container;
        DefaultControllerFactory defaultControllerFactory;

        public MefControllerFactory(CompositionContainer compositionContainer)
        {
            container = compositionContainer;
            defaultControllerFactory = new DefaultControllerFactory();
        }

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            IController controller = null;

            if (controllerName != null)
            {
                var export = this.container.GetExports<IController, IControllerMetadata>()
                                                 .Where(c => c.Metadata.Name.Equals(controllerName, StringComparison.InvariantCultureIgnoreCase))
                                                 .FirstOrDefault();
                if (export != null)
                    controller = export.Value;
            }

            if (controller == null)
                return this.defaultControllerFactory.CreateController(requestContext, controllerName);

            return controller;
        }

        public void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if (disposable != null)
                disposable.Dispose();
        }
    }
}